import { fabric } from 'fabric';

Object.assign(fabric.Object.prototype, {
  // 默认设置坐标位置为中心点
  originX: 'center',
  originY: 'center',
  // 元素缩小到最小时，不要反向放大
  minScaleLimit: 0,
  lockScalingFlip: true
} as Partial<fabric.Object>);

// 默认设置Shape的边框宽度和边框缩放设置
[fabric.Rect, fabric.Ellipse, fabric.Triangle].forEach((obj) => {
  obj.prototype.strokeWidth = 2;
  obj.prototype.strokeUniform = true;
});

// 将图片的渲染方式改为居中展示
fabric.Image.prototype._renderFill = function (ctx): void {
  const elementToDraw = this._element;
  if (!elementToDraw) {
    return;
  }
  const scaleX = this._filterScalingX;
  const scaleY = this._filterScalingY;
  const w = this.width;
  const h = this.height;
  const min = Math.min;
  const max = Math.max;
  // crop values cannot be lesser than 0.
  const cropX = max(this.cropX, 0);
  const cropY = max(this.cropY, 0);
  const elWidth = elementToDraw.naturalWidth || elementToDraw.width;
  const elHeight = elementToDraw.naturalHeight || elementToDraw.height;
  const sX = cropX * scaleX;
  const sY = cropY * scaleY;
  // the width height cannot exceed element width/height, starting from the crop offset.
  const sW = min(w * scaleX, elWidth - sX);
  const sH = min(h * scaleY, elHeight - sY);
  const maxDestW = min(w, elWidth / scaleX - cropX);
  const maxDestH = min(h, elHeight / scaleY - cropY);
  // 改为居中展示
  const x = -maxDestW / 2; // 原始逻辑为 -w/2
  const y = -maxDestH / 2; // 原始逻辑为 -h/2

  elementToDraw &&
    ctx.drawImage(elementToDraw, sX, sY, sW, sH, x, y, maxDestW, maxDestH);
};

declare module 'fabric' {
  namespace fabric {
    let devicePixelRatio: number;
    let window: Window & {
      webkitDevicePixelRatio?: number;
      mozDevicePixelRatio?: number;
    };
  }
}
